package top.yi2911.lifeUtils.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Adapter
import top.yi2911.lifeUtils.databinding.ActivityMainItemBinding
import top.yi2911.lifeUtils.model.Features

/**
 *Author:liang jian
 *Date:2021-01-15  16:13
 *Description:
 */
class MainRecycleAdapter(val datas: Array<Features>, val mainView: Int) :
    Adapter<MainViewHolder>() {

    private lateinit var onItemClickListener: OnItemClickListener

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainViewHolder {
        val itemBinding = DataBindingUtil.inflate<ActivityMainItemBinding>(
            LayoutInflater.from(parent.context),
            mainView,
            parent,
            false
        )
        return MainViewHolder(itemBinding.root, itemBinding)
    }

    override fun onBindViewHolder(holder: MainViewHolder, position: Int) {
        holder.setValue(datas[position])
        holder.itemView.setOnClickListener{
            onItemClickListener.onItemClick(holder.itemView,position)
        }

        holder.itemView.setOnLongClickListener {
            onItemClickListener.onItemLongClick(holder.itemView,position)
            true
        }
    }

    override fun getItemCount(): Int {
        return datas.size
    }

    fun setOnItemClickListener(listener: OnItemClickListener) {
        this.onItemClickListener = listener
    }
}

interface OnItemClickListener {
    fun onItemClick(view: View, position: Int)
    fun onItemLongClick(view: View, position: Int)
}

class MainViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    lateinit var binding: ActivityMainItemBinding

    constructor(itemView: View, binding: ActivityMainItemBinding) : this(itemView) {
        this.binding = binding
    }

    fun setValue(features: Features) {
        binding.mainItemImg.setBackgroundResource(features.pic)
        binding.mainItemText.text = features.name
    }
}